package com.currency.mall.ui.login;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.entity.LoginBean;
import com.currency.mall.event.LoginEvent;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.widget.VerifyCodeView;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbusines.entity.ResponseBean;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/1/7.
 */

public class SpeedLoginActivity extends BaseActivity {

    @BindView(R.id.et_input_phone)
    EditText etInputPhone;
    @BindView(R.id.rl_phone)
    RelativeLayout rlPhone;
    @BindView(R.id.et_phone_verifyCode)
    EditText etPhoneVerifyCode;
    @BindView(R.id.verifyCodeView)
    VerifyCodeView verifyCodeView;
    @BindView(R.id.et_verifyCode)
    EditText etVerifyCode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.btn_login)
    Button btnLogin;
    private MyTime myTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speed_login);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        myTime = new MyTime(60000, 1000);
        btnLogin.getBackground().setAlpha(50);
        btnLogin.setClickable(false);
        etInputPhone.addTextChangedListener(phoneTextWatcher);
        etPhoneVerifyCode.addTextChangedListener(textWatcher);
        etVerifyCode.addTextChangedListener(textWatcher);
        verifyCodeView.loadUrl(Constant.IMAGECODE);
        verifyCodeView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                verifyCodeView.reload();
                return false;
            }
        });
    }

    TextWatcher phoneTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String strInputPhone = etInputPhone.getText().toString().trim();
            String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
            String strVerifyCode = etVerifyCode.getText().toString().trim();
            if (TextUtils.isEmpty(strInputPhone) || TextUtils.isEmpty(strPhoneVerifyCode) || TextUtils.isEmpty(strVerifyCode) || TextUtils.isEmpty(s)) {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(50);
                btnLogin.setClickable(false);
            } else {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(250);
                btnLogin.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                rlPhone.setVisibility(View.INVISIBLE);
            } else {
                rlPhone.setVisibility(View.VISIBLE);
            }
        }
    };

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String strInputPhone = etInputPhone.getText().toString().trim();
            String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
            String strVerifyCode = etVerifyCode.getText().toString().trim();
            if (TextUtils.isEmpty(strInputPhone) || TextUtils.isEmpty(strPhoneVerifyCode) || TextUtils.isEmpty(strVerifyCode) || TextUtils.isEmpty(s)) {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(50);
                btnLogin.setClickable(false);
            } else {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(250);
                btnLogin.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String str = sdf.format(date);
            tvSendCode.setText("验证码"+"(" + millisUntilFinished / 1000+"s"+ ")");
        }

        @Override
        public void onFinish() {
            tvSendCode.setText("获取验证码");
            tvSendCode.setClickable(true);
        }
    }


    @OnClick({R.id.ll_back, R.id.rl_phone, R.id.btn_login, R.id.tv_send_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.rl_phone:
                etInputPhone.setText("");
                rlPhone.setVisibility(View.GONE);
                break;
            case R.id.btn_login:
                checkCode();
                break;
            case R.id.tv_send_code:
                if(sendCodeVerification()){
                    sendCode();
                }
                break;
        }
    }

    public void sendCodesuccess() {
        myTime.start();
        tvSendCode.setClickable(false);
    }

    public void phoneVerifyCodeFail() {
        verifyCodeView.loadUrl(Constant.IMAGECODE);
    }

    public void checkCodesuccess() {
        login();
    }


    public void sendCode() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("phoneOremail", etInputPhone.getText().toString().trim());
        hashMap.put("tempName", "9374734");
        hashMap.put("imgCode", etPhoneVerifyCode.getText().toString().trim());
        hashMap.put("type", "LOGO");
        NetWork.getLoginApi().sendcode(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        String code = responseBean.getCode();
                        if (code.equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("短信发送成功，请注意查收,5分钟内有效", 200);
                            sendCodesuccess();
                        } else if (code.equals("1011")) {
                            ToastUitl.show(responseBean.getMsg(), 200);
                            phoneVerifyCodeFail();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }

                    }
                });
    }

    public void checkCode() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("code", etVerifyCode.getText().toString().trim());
        hashMap.put("mobile", etInputPhone.getText().toString().trim());
        NetWork.getLoginApi().checkcode(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        String code = responseBean.getCode();
                        if (code.equals(Constant.SUCCESS_CODE)) {
                            checkCodesuccess();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }

                    }
                });
    }

    public void login() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("mobile", etInputPhone.getText().toString().trim());
        NetWork.getLoginApi().quickLogin(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        if (loginBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("登录成功", 200);
                            PreferenceUtils.saveToken(loginBean.getToken());
                            EventBus.getDefault().post(new LoginEvent(LoginEvent.LOGIN_STATUS));
                        } else {
                            ToastUitl.show(loginBean.getMsg(), 200);
                        }
                    }
                });
    }

    private boolean sendCodeVerification() {
        String setInputPhone = etInputPhone.getText().toString().trim();
        String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
        if("".equals(setInputPhone)){
            ToastUitl.show("请输入手机号码", 200);
            return false;
        }else if (setInputPhone.length()<10) {
            ToastUitl.show("请输入正确的手机", 200);
            return false;
        }else if ("".equals(strPhoneVerifyCode)) {
            ToastUitl.show("请输入图形验证码", 200);
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTime != null) {
            myTime.cancel();
        }
    }
}
